package com.erbadagang.springcloud.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description 限流 KEY 的 Bean ，通过解析请求的来源 IP 作为限流 KEY，这样我们就能实现基于 IP 的请求限流。
 * @ClassName: GatewayConfig
 * @author: 郭秀志 jbcode@126.com
 * @date: 2020/7/29 15:26
 * @Copyright:
 */
@Configuration
public class GatewayConfig {

    @Bean
    public KeyResolver ipKeyResolver() {
        return new KeyResolver() {

            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                // 获取请求的 IP
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }

        };
    }

}
